package com.maple.controller.admin;

import com.maple.dto.DishDTO;
import com.maple.dto.DishPageQueryDTO;
import com.maple.entity.Dish;
import com.maple.result.PageResult;
import com.maple.result.Result;
import com.maple.service.DishService;
import com.maple.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/admin/dish")
@Slf4j
public class DishController {

    @Autowired
    DishService dishService;
    @Autowired
    RedisTemplate redisTemplate;

    @GetMapping("/page")
    public Result<PageResult> page(DishPageQueryDTO pageQueryDTO){
        log.info("菜品分页查询：{}",pageQueryDTO);
        PageResult pageResult = dishService.page(pageQueryDTO);
        return Result.success(pageResult);
    }


    @GetMapping("/{id}")
    public Result<DishVO> queryById(@PathVariable String id){
        log.info("根据id查询菜品：{}", id);
        DishVO dish = dishService.queryById(id);
        return Result.success(dish);
    }


    @GetMapping("/list")
    public Result<List<DishVO>> queryByCategoryId(@RequestParam String categoryId){
        log.info("根据分类id查询菜品：{}", categoryId);
        List<DishVO> dishVO = dishService.queryByCategoryId(categoryId);
        return Result.success(dishVO);
    }


    @PostMapping
    public Result save(@RequestBody DishDTO dishDTO){
        log.info("新增菜品：{}", dishDTO);
        dishService.save(dishDTO);
        deleteRedis("dish_*");
        return Result.success();
    }


    @PostMapping("/status/{status}")
    public Result changeStatus(@PathVariable Integer status, String id){
        log.info("更新菜品状态：{}", status);
        dishService.changeStatus(status, id);
        deleteRedis("dish_*");
        return Result.success();
    }

    @PutMapping
    public Result update(@RequestBody DishDTO dishDTO){
        log.info("修改菜品数据：{}", dishDTO);
        dishService.update(dishDTO);
        deleteRedis("dish_*");
        return Result.success();
    }

    @DeleteMapping
    public Result deleteById(@RequestParam List<Long> ids){
        log.info("批量删除：{}", ids);
        dishService.deleteById(ids);
        deleteRedis("dish_*");
        return Result.success();
    }


    private void deleteRedis(String pattern){
        redisTemplate.delete(pattern);
    }
}
